#include "dri_aip16c22.h"
#include "kernel/os/os.h"
#include "driver/chip/hal_gpio.h"
#include "driver/chip/hal_i2c.h"
#include <string.h>
#include <stdbool.h>

// 背光控制引脚
#define GPIO_LCD_EN_PORT             GPIO_PORT_A
#define GPIO_LCD_EN_PIN              GPIO_PIN_14

#define IIC_ID 					I2C1_ID
#define IIC_FREQ				200000
#define IIC_RTC_ADDR_7BIT		    (0x7E >> 1)

static uint8_t i2c_init()
{
	HAL_Status status = HAL_ERROR;

	I2C_InitParam initParam;
	initParam.addrMode = I2C_ADDR_MODE_7BIT;
	initParam.clockFreq = IIC_FREQ;

	status = HAL_I2C_Init(IIC_ID, &initParam);
	if (status != HAL_OK) {
		printf("IIC init error %d\n", status);
		return HAL_ERROR;
	}
	printf("HAL_I2C_Init success \n");
	return HAL_OK;
}

/**
 * @brief  初始化
 * 
 * @return true 
 * @return false 
 */
bool  AiP16C22_init(){
   uint8_t  result =  i2c_init();
   if (result != HAL_OK)
   {
        return false ;
   }

    // 背光引脚初始化
	GPIO_InitParam param;
	param.driving = GPIO_DRIVING_LEVEL_1;
	param.mode = GPIOx_Pn_F1_OUTPUT;
	param.pull = GPIO_PULL_NONE;
	HAL_GPIO_Init(GPIO_LCD_EN_PORT,GPIO_LCD_EN_PIN , &param);
    AiP16C22_backlight(true);

	AiP16C22_write_cmd(0x9c, 0x00);    //LCD bias，LCD on/off，LCD frequency    
	AiP16C22_write_cmd(0xc0, 0x00);     //LCD blink  OFF	
    AiP16C22_clearscreen();
   return true ;
}

/**
 * @brief 写数据
 * 
 * @param addr 
 * @param data 
 * @param data_len 
 */
void AiP16C22_write_data(uint8_t addr,  uint8_t *data, uint32_t data_len){
	uint32_t len = HAL_I2C_Master_Transmit_Mem_IT(IIC_ID, IIC_RTC_ADDR_7BIT, addr,
														I2C_MEMADDR_SIZE_8BIT, data , data_len);
	if (len != data_len) {
		printf("to write size=%d, but i2c write size=%d,devAddr = %d\n", data_len, len, addr);
		return ;
	}else{
		//printf("i2c write success\n ");
	}
}

/**
 * @brief 写命令
 * 
 * @param addr 
 * @param data 
 */
void AiP16C22_write_cmd(uint8_t addr,  uint8_t data){
	uint32_t len = HAL_I2C_Master_Transmit_Mem_IT(IIC_ID, IIC_RTC_ADDR_7BIT, addr,
														I2C_MEMADDR_SIZE_8BIT, &data , 1);
	if (len != 1) {
		printf("to write size=%d, but i2c write size=%d,devAddr = %d\n", 1, len, addr);
		return ;
	}else{
		//printf("i2c write success \n");
	}
}

/**
 * @brief  背光控制
 * 
 * @param open 
 */
void AiP16C22_backlight(bool open){
    	HAL_GPIO_WritePin(GPIO_LCD_EN_PORT, GPIO_LCD_EN_PIN, open?  GPIO_PIN_HIGH: GPIO_PIN_LOW );
}

/**
 * @brief 清除屏幕
 * 
 */
void AiP16C22_clearscreen(){
	char buff[22] = {0x00};
	AiP16C22_write_data( 0x00 ,  buff , sizeof(buff));
}